package com.springboot.show_web.controller;

import com.springboot.show_web.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yaosheng on 2019/11/9.
 */
@ControllerAdvice
public class MyExceptionHandler {

    //浏览器与客户端都返回的是Json数据
    @ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public String handlerException(Exception e){
        Map<String,Object> map = new HashMap<> ();
        map.put ("code","user.notexist");
        map.put ("message",e.getMessage());
        return map;
    }

    @ExceptionHandler(UserNotExistException.class)
    public String handlerException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<> ();
        //传入自己的默认状态码
        /**
         * Integer statusCode = (Integer) request
         .getAttribute("java.servlet.error.status_code")'
         */
        request.setAttribute ("javax.servlet.error.status_code", 500);
        map.put ("code", "user.notexist");
        map.put ("message", "用户出错啦!");
        request.setAttribute ("ext", map);
        //转发到/error
        return "forward:/error";
    }
}